import { defineStore } from "pinia";
import { getToken, setToken } from "@/utils/auth"; // 使用核心auth封装组件管理token
import { ref } from "vue";
import { getUserProfile } from "@/api/auth/user/user.js";

export const useUserStore = defineStore("userStore", {
  state: () => ({
    profile: ref({
      name: "请登录",
    }),
  }),
  persist: true, // 启用持久化
  actions: {
    setUserToken(token1) {
      setToken(token1);
    },
    getUserToken() {
      return getToken();
    },
    getProfile() {
      return this.profile;
    },
    setProfile(profileInfo) {
      this.profile = profileInfo;
    },
    async updateProfile() {
      const resProfile = await getUserProfile();
      console.log("获取用户信息", resProfile);
      this.setProfile(resProfile.data);
    },

    // 登录后续执行的操作，根据res内容执行（能执行这个函数代表成功获取了token
    // 会执行设置token和获取profile
    async loginSuccess(res) {
      this.setUserToken(res.access_token);
      console.log(this.getUserToken());
      // 获取用户信息
      this.updateProfile();
    },
    logout() {
      this.profile = { name: "请登录" };
      this.setUserToken("");
    },
    /**
     * 获取用户名称
     * @returns
     */
    getUserName() {
      var name = this.profile.name;
      if (name === null || name.length === 0) {
        return "暂无名称";
      }
      return name;
    },
  },
});
